import siteInfo from '../siteinfo.js';
import $util from "@/utils/util";
import $store from "@/store/index.js"
import $i18n from "@/utils/i18n.js" // 多语言
import $api from '@/api/index.js';


const promisic = (func) => {
	return (params = {}) => {
		return new Promise((resolve,reject) => {
			// 构造参数
			const args =  Object.assign(params,{
				success: (res) => {
					let data = res.data
					// 判断data不是json对象时进行转化
					if($util.isJSON(data)) data = JSON.parse(data)
					// console.log(res)
					if(data.code !== 200){
						$util.showToast(data.msg,function(){
							// 关闭加载
							$util.hideAll()
						})
					}
					// 10001：未登录 10002：token错误 10003：用户信息不存在 10004：用户被停用 10005：登录失效  10006：触发接口安全限制
					if(data.errorCode == '10001' || data.errorCode == '10002' || data.errorCode == '10003' || data.errorCode == '10004' || data.errorCode == '10005' || data.errorCode == '10006'){
						// 存在errorCode清除登录状态并返回登录页面
						// 清理缓存
						$util.clearCache(true);
						let routes = getCurrentPages(); // 获取当前打开过的页面路由数组  
						let curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由
						// console.log(curRoute)
						if(curRoute != 'pages/auth/login'){
							uni.navigateTo({
								url: '/pages/auth/login'
							});
						}

					}
					// 返回res
					resolve(res);
				},
				fail: (error) => {
					uni.onNetworkStatusChange(function (res){
						if(!res.isConnected){
							// 无网络
							$util.showToast('网络连接失败');
						}
					})
					$util.showToast('服务器连接失败');
					return false;
					// 服务器连接失败
				},
				complete:()=>{
					// 成功失败均执行此回调
					uni.hideLoading();
				}
			});
			func(args);
		});
	}
}

const is_H5 = false;

const formatUrl = function(url) {
	let siteroot = siteInfo.siteroot
	if(is_H5){
		siteroot = location.origin
	}
	return `${siteroot}/api/v1/${url}`
}

const httpType = ["post", "get"]
const formatReq = function() {
	let req = {};
	let sysInfo = uni.getSystemInfoSync();
	httpType.forEach((type) => {
		req[type] = async function(url, data, is_login = true) {
			return (await promisic(uni.request)({
			    url:formatUrl(url),
			    data,
			    method:type,
				header: {
					'authToken' : is_login ? uni.getStorageSync('authToken') : '',
					'appId': sysInfo.appId,
					'appversion': sysInfo.appVersion,
					'platform': sysInfo.uniPlatform,
					'deviceId': sysInfo.deviceId,
					'osName': sysInfo.osName,
				},
			})).data
		}
	})
	return req;
}
const http = formatReq();

const uploadFile = async(url,{
	name = "file",
	filePath,
	formData = {
		type: 'picture'
	}
} = {} ) => {
	url = formatUrl(url)
	let sysInfo = uni.getSystemInfoSync();
	return (await promisic(uni.uploadFile)({
	    url,
	    filePath,
	    name,
	    header: {
			'authToken' : uni.getStorageSync('authToken'),
			'appId': sysInfo.appId,
			'appversion': sysInfo.appVersion,
			'platform': sysInfo.uniPlatform,
			'deviceId': sysInfo.deviceId,
			'osName': sysInfo.osName,
	    },
	    timeout:5000,
	    formData,
	})).data

}
export {
	http,
	uploadFile
}